var nick = "Anomymous Coward";
var color = [0, 0, 0];
//var socket; // = io.connect("213.103.197.232:12345");
var socket = io.connect("http://localhost:12345/");
var col = randomColor();

function knapp_tryck() {
    console.log("ansluter...");
    socket = io.connect("http://localhost:12345");
    console.log("anslutit...");
    socket.on("recieve log", function(log) {
        console.log("definierar......");
        console.log("got a 'recieve log' request, here's the log:");
        console.log(log);
        var str = "<div id='helachatten'> <div id='conv'>";
        for (var i=0; i<log.length; i++) {
            //str += ("<p style='color: "+ color + "'>" + log[i] + "</p>");
            str += ("<div id='indtext'>"+log[i]+'</div><br>')                         
        }
        str += "</div>"
        str += "<div id= 'textfield'><div id='flyttanick'>" + nick + "</div><div id='flytta'><textarea id='textruta' onkeydown = 'if (event.keyCode == 13) {sendmessage(this.value);};' rows=3 cols=40> </textarea> </div></div>"
        "</div>"
        console.log(str)  
        document.getElementById("the paragraph").innerHTML=str;
        var objDiv = document.getElementById("conv");
        objDiv.scrollTop = objDiv.scrollHeight;
    });
    socket.emit("get log", 100);
    var knapp = document.getElementById("startbutton");
    console.log("knappen är:");
    console.log(knapp);
    knapp.textContent="avsluta chatt";
    knapp.onclick = function() {
        socket.emit('disconnect');
        socket = null;
        document.getElementById("the paragraph").innerHTML="";
        knapp.textContent="starta chatt";
        knapp.onclick = knapp_tryck;
    }
    console.log(knapp);
    
}

function randomColor() {
    var col = "#";
    var possible = "0123456789ABCDEF"

    for( var i=0; i < 6; i++ )
        col += possible.charAt(Math.floor(Math.random() * possible.length));

    return col;
}

function sendmessage(message) {
    console.log("client: senging message... ", message);
    socket.emit("send message", nick + message);
    socket.emit("get log", 1000);
}



function changeNick(newNick) {
    socket.emit("get log", 100);
    nick = "<font color='" + col + "'>" + newNick + ":</font>";
    socket.emit("get log", 100);
};

